import { Spin } from "antd";
import "./index.css";
import { createRoot } from "react-dom/client";

const Loading = (props) => {
  let { visible, size = "large", tip = "加载中。。", indicator = null } = props;

  let loadingEl = document.createElement("div");
  loadingEl.id = "loadingRoot";

  //关闭的方法
  function close() {
    //visible为false 移除
    let loadingDom = document.getElementById("loadingRoot");
    if (loadingDom) {
      document.body.removeChild(loadingDom);
    }
  }

  if (visible) {
    let loadingDom = document.getElementById("loadingRoot");
    if (!loadingDom) {
      document.body.appendChild(loadingEl);

      let SpinCom = indicator ? (
        <Spin
          className="spin"
          size={size}
          tip={tip}
          indicator={indicator}
        ></Spin>
      ) : (
        <Spin className="spin" size={size} tip={tip}></Spin>
      );

      let reactNode = <div className="loading">{SpinCom}</div>;
      //创建render准备
      let lodaingBox = createRoot(loadingEl);
      //render到页面
      lodaingBox.render(reactNode);
    }
  } else {
    //visible改变 自动关闭
    close();
  }
  //暴露API 方法
  return close;
};

export default Loading;
